package com.shelpe.services.sinbad.controller.actionLog.impl.keyword;

import java.util.Locale;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Service;

import com.shelpe.services.sinbad.controller.actionLog.ActionLogDto;
import com.shelpe.services.sinbad.controller.actionLog.ActionLogService;
import com.shelpe.services.sinbad.controller.actionLog.KeywordVo;
import com.shelpe.services.sinbad.entity.jpa.Adgroup;
import com.shelpe.services.sinbad.entity.jpa.Campaign;
import com.shelpe.services.sinbad.entity.jpa.KeywordsLog;

@Service
public class KeywordUpdatePriceConverter extends ActionLogService {
	@Autowired
	private MessageSource messageSource;

	@Override
	public ActionLogDto convertKeywrod(KeywordsLog entity, Map<Long, Campaign> campaignMap,
			Map<Long, Adgroup> adgroupMap) {
		boolean keywordUpdatePriceConverter = entity.getAction() == KeywordsLog.Action.AUTO_CHANGE_PRICE
				|| entity.getAction() == KeywordsLog.Action.MANUAL_CHANGE_PRICE
				|| entity.getAction() == KeywordsLog.Action.SEMIAUTO_EXEC_UPDATE;
		if (keywordUpdatePriceConverter) {
			ActionLogDto dto = new ActionLogDto();
			dto.from(entity);
			if (StringUtils.isNotBlank(entity.getNote())) {
				KeywordVo vo = this.unserializeKeyword(entity.getNote());
				if (vo != null && vo.getOldPo() != null && vo.getNewPo() != null) {
					Adgroup adgroup = adgroupMap.get(vo.getNewPo().getAdgroupId());
					if (adgroup != null && StringUtils.isNotBlank(this.from(vo))) {
						String[] params = { adgroup.getProductName(), entity.getKeyword(), this.from(vo) };
						dto.setReason(
								messageSource.getMessage("message.keyword.updateprice.reason", params, Locale.ENGLISH));
						return dto;
					}
				}
			}
		}
		return null;
	}

	private String from(KeywordVo vo) {
		String message = "";
		if (!vo.getOldPo().getMaxPrice().equals(vo.getNewPo().getMaxPrice())) {
			message = "pc出价由" + (float) vo.getOldPo().getMaxPrice() / 100 + "更新为"
					+ (float) vo.getNewPo().getMaxPrice() / 100 + "元";
		}

		if (!vo.getOldPo().getMaxMobilePrice().equals(vo.getNewPo().getMaxMobilePrice())) {
			if (StringUtils.isBlank(message)) {
				message = "无线出价由" + (float) vo.getOldPo().getMaxMobilePrice() / 100 + "更新为"
						+ (float) vo.getNewPo().getMaxMobilePrice() / 100 + "元";
			} else {
				message = ",无线出价由" + (float) vo.getOldPo().getMaxMobilePrice() / 100 + "更新为"
						+ (float) vo.getNewPo().getMaxMobilePrice() / 100 + "元";
			}
		}
		return message;
	}
}
